class SessionsController < ApplicationController
  skip_before_action :store_previous_url
  def create
    @user = User.find_or_create_from_auth_params(auth_params)
    sign_in @user
    redirect_back_or_default root_path
  end

  def omniauth
    redirect_to root_path and return unless request.env['omniauth.auth']
    user = User.find_or_create_by(id: omniauth_params[:id])
    user.update(omniauth_params)
    sign_in user
    redirect_back_or_default root_path
  end

  def sign_out
    token = current_user&.token
    session[:user_id] = nil
    redirect_to "https://account.geekpark.net/logout?referrer=#{params[:redirect_url] || request.referrer || root_url}&access_token=#{token}"
  end

  private

  def omniauth_params
    params = ActionController::Parameters.new(request.env['omniauth.auth'])
    params.merge(params[:info])
          .merge(params[:credentials])
          .merge({ expires_at: Time.at(params[:credentials][:expires_at]), id: params[:uid] })
          .permit(:id, :token, :refresh_token, :expires_at)
  end

  def sign_in user
    session[:user_id] = user.id
  end

  def auth_params
    request.env['omniauth.auth']
  end
end
